<?php
/**
 * Created by PhpStorm.
 * User: this
 * Date: 2018/12/5
 * Time: 9:18
 */

namespace app\admin\controller;
use app\admin\model\Articles;
use think\cache;

class Article extends Base{
    public function _initialize(){
        $this->isLogin();
    }

    /**
     * 文章列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index(){
        $model = new Articles();
        $article = $model->getPage('','bb_article.article_id,bb_article.article_title,bb_article.article_author,bb_article.article_add_time,bb_article.article_edit_time,bb_article.article_read_no,bb_article.article_status,bb_article_category.article_cate_name');
        foreach ($article as &$v){
            $v['article_add_time'] = date('Y-m-d H:i:s',$v['article_add_time']);
            $v['article_edit_time'] = date('Y-m-d H:i:s',$v['article_edit_time']);
        }

        $page = $article->render();
        $this->assign('page',$page);
        $this->assign('article',$article);
        $this->assign('site_title','文章列表-管理后台-百步园艺');
        return $this->fetch('index');
    }

    /**
     * 修改文章
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit(){
        $article_id = input('article_id');
        if(!$article_id){
            ajaxReturn(0,'参数错误!',0);
        }
        $model = new Articles;
        //查询分类
        $cate = $model->cateList(array('article_cate_pid'=>0),'article_cate_id,article_cate_name');
        $child = $model->cateList(array('article_cate_pid'=>array('neq',0)),'article_cate_id,article_cate_name,article_cate_pid');

        $info = $model->getOne(array('article_id'=>$article_id),'article_id,article_title,article_author,article_content,article_abstract,article_status,article_category_id');
//        print_r($info);exit;
        //表单提交
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['article_title']) || !$data['article_title']){
                ajaxReturn(0,'标题不能为空!',0);
            }
            if(!isset($data['article_content']) || $data['article_content'] =='<p><br></p>'){
                ajaxReturn(0,'内容不能为空!',0);
            }

            if(isset($data['article_id']) && !$data['article_id']){
                unset($data['article_id']);
            }

            //正则匹配图片
            $preg = '/<img.*?src="(.*?)".*?\/?>/i';
            $img = array();
            $del_img = array();
            preg_match_all($preg,$data['article_content'],$img);
            preg_match_all($preg,$info['article_content'],$y_img);

            //存在图片
            if($img[1]){
                $path = 'public/uploads/article/'.date('Ymd',time());
                //将img标签替换成+rep+ 以便替换
                $data['article_content'] = $content = preg_replace($preg,'+rep+', $data['article_content']);
                $i = 0;
                foreach ($img[1] as $k => $v){
                    //转义base64文件并保存
                    preg_match('/^(data:\s*image\/(\w+);base64,)/',$v, $result);
//                    if(strpos('','',''))
                    if($result || !strpos($v,'public/uploads/article/')){
                        if($result){
                            $src = '/baibu/'.$path.'/'.base64_image_content($v,ROOT_PATH.$path,makeSalt(8));
                        }else{
                            $src = $v;
                        }
                        if(isset($y_img[1][$i])){
                            $del_img[] = $y_img[1][$i];
                        }
                    }else{
                        $src = $y_img[1][$i];
                    }
                    $i ++;
                    $data['article_content'] = get_img_thumb_url($data['article_content'],$src);
                }
            }else{
                foreach ($y_img[1] as $k=>$v){
                    $del_img[] = $v;
                }
            }
            //转义html标签
            $data['article_edit_time'] = time();
            $result = $model->edit(array('article_id'=>$data['article_id']),$data);
            if($result){
                if($del_img){
                    foreach ($del_img as $item){
                        del_file(substr(ROOT_PATH,0,-7).$item);
                    }
                }
                ajaxReturn('/baibu/admin/Article/','修改成功!',1);
            }else{
                ajaxReturn(0,'修改失败!',0);
            }

        }

        if($cate){
            foreach ($cate as &$v){
                $v = $v->toArray();
                $v['child'] = array();
                if($child){
                    foreach ($child as $value){
                        if($v['article_cate_id'] == $value['article_cate_pid']){
                            $v['child'][] = $value;
                        }
                    }
                }
            }
        }
        $this->assign('info',$info);
        $this->assign('cate',$cate);
        $this->assign('site_title',"修改文章-管理后台-百步园艺");
        $this->assign('nav','修改文章');
        $this->assign('url','/baibu/admin/Article/edit');
        return $this->fetch('add');
    }

    /**
     * 修改状态
     */
    public function status(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        $update['article_status'] = $_GET['article_status'];
        $condition['article_id'] = $_GET['article_id'];
        $article = new Articles;
        $result = $article->edit($condition,$update);
        if($result){
            switch ($update['article_status']){
                case 1:
                    $data['img'] = '/baibu/public/static/image/default/dui.png';
                    $data['name'] = "article_id={$condition['article_id']}&article_status=0";
                    break;
                default :
                    $data['img'] = '/baibu/public/static/image/default/cuo.png';
                    $data['name'] = "article_id={$condition['article_id']}&article_status=1";
                    break;
            }
            ajaxReturn($data,'操作成功!',1);
        }else{
            ajaxReturn(0,'操作失败!',0);
        }
    }

    /**
     * 删除文章
     * @throws \think\exception\PDOException
     */
    public function del(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        if(gettype($_GET['article_id']) == 'array'){
            $condition['article_id'] = array('in',$_GET['article_id']);
        }else{
            $condition['article_id'] = $_GET['article_id'];
        }
        $article = new Articles;
        $article->startTrans();
        try{
            $info = $article->getList($condition,'article_content');

            foreach ($info as $v){
                preg_match_all('/<img.*?src="(.*?)".*?\/?>/i',$v['article_content'],$img);
                if($img[1]){
                    foreach ($img[1] as $key=>$value){
                        del_file(substr(ROOT_PATH,0,-7).$value);
                    }
                }
            }
            $article->del($condition);
            $article->commit();
            ajaxReturn($_GET['article_id'],'删除成功!',1);
        }catch (\Exception $e){
            $article->rollback();
            ajaxReturn(0,'删除失败!',0);
        }
//        $result = $article->del($condition);
//        if($result){
//            ajaxReturn($_GET['article_id'],'删除成功!',1);
//        }else{
//            ajaxReturn(0,'删除失败!',0);
//        }
    }

    /**
     * 发布文章
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add(){
        $model = new Articles;
        //查询分类
        $cate = $model->cateList(array('article_cate_pid'=>0),'article_cate_id,article_cate_name');
        $child = $model->cateList(array('article_cate_pid'=>array('neq',0)),'article_cate_id,article_cate_name,article_cate_pid');
        //表单提交
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['article_title']) || !$data['article_title']){
                ajaxReturn(0,'标题不能为空!',0);
            }
            if(!isset($data['article_content']) || $data['article_content'] =='<p><br></p>'){
                ajaxReturn(0,'内容不能为空!',0);
            }

            if(isset($data['article_id']) && !$data['article_id']){
                unset($data['article_id']);
            }

            //正则匹配图片
            $preg = '/<img.*?src="(.*?)".*?\/?>/i';
            $img = array();
            preg_match_all($preg,$data['article_content'],$img);
            //存在图片
            if($img){
                $path = 'public/uploads/article/'.date('Ymd',time());
                //将img标签替换成+rep+ 以便替换
                $data['article_content'] = $content = preg_replace($preg,'+rep+', $data['article_content']);
                foreach ($img[1] as $k => $v){
                    preg_match('/^(data:\s*image\/(\w+);base64,)/',$v, $result);
                    if($result || !strpos($v,'public/uploads/article/')) {
                        if ($result) {
                            //转义base64文件并保存
                            $src = '/baibu/' . $path . '/' . base64_image_content($v, ROOT_PATH . $path, makeSalt(8));
                        } else {
                            $src = $v;
                        }
                    }
//                    $src = '/baibu/'.$path.'/'.base64_image_content($v,ROOT_PATH.$path,makeSalt(8));
                    $data['article_content'] = get_img_thumb_url($data['article_content'],$src);
                }
            }
            $data['article_add_time'] = time();
            $data['article_edit_time'] = time();
            $result = $model->add($data);
            if($result){
                ajaxReturn('/baibu/admin/Article/','发布成功!',1);
            }else{
                ajaxReturn(0,'发布失败!',0);
            }

        }

        if($cate){
            foreach ($cate as &$v){
                $v = $v->toArray();
                $v['child'] = array();
                if($child){
                    foreach ($child as $value){
                        if($v['article_cate_id'] == $value['article_cate_pid']){
                            $v['child'][] = $value;
                        }
                    }
                }
            }
        }
        $this->assign('cate',$cate);
        $this->assign('site_title',"发布文章-管理后台-百步园艺");
        $this->assign('nav','发布文章');
        $this->assign('url','/baibu/admin/Article/add');
        return $this->fetch('add');
    }

    /**
     * 分类列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function cateList(){
        $article = new Articles();
        $cate = $article->catePage('','article_cate_id,article_cate_name,article_cate_remark,article_cate_status');
        $page = $cate->render();
        $this->assign('cate',$cate);
        $this->assign('site_title','文章分类-管理后台-百步园艺');
        $this->assign('page',$page);
        return $this->fetch('category');
    }

    /**
     * 分类添加
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cateAdd(){
        $article = new Articles;
        $condition['article_cate_pid'] = 0;
        $cate = $article->cateList($condition,'article_cate_id,article_cate_name');
        if(request()->isPost()){
            if($_POST){
                $data = input('post.');
                if(!isset($data['article_cate_name']) || !$data['article_cate_name']){
                    ajaxReturn(0,'分类不能为空!',0);
                }
                if(!isset($data['article_cate_pid'])){
                    ajaxReturn(0,'上级分类不能为空!',0);
                }
                if(isset($data['article_cate_id']) && !$data['article_cate_id']){
                    unset($data['article_cate_id']);
                }
                $data['article_cate_time'] = time();
                $result = $article->cateAdd($data);
                if($result){
                    ajaxReturn('/baibu/admin/Article/cateList','添加成功!',1);
                }else{
                    ajaxReturn(0,'添加失败!',0);
                }
            }
        }
        $this->assign('cate',$cate);
        $this->assign('site_title','添加文章分类-管理后台-百步园艺');
        $this->assign('nav','添加分类');
        $this->assign('url','/baibu/admin/Article/cateAdd');
        return $this->fetch('cate_add');
    }

    /**
     * 分类修改
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cateEdit(){
        $article_cate_id = input('article_cate_id');
        if(!$article_cate_id){
            ajaxReturn(0,'参数错误!',0);
        }
        $article = new Articles();
        $info = $article->cateOne(array('article_cate_id'=>$article_cate_id),'article_cate_id,article_cate_name,article_cate_remark,article_cate_status,article_cate_pid');
        if(request()->isPost()){
            $data = $_POST;
            $condition['article_cate_id'] = $data['article_cate_id'];
            $result = $article->cateEdit($condition,$data);
            if($result){
                ajaxReturn('/baibu/admin/Article/cateList','修改成功!',1);
            }else{
                ajaxReturn(0,'修改失败!',0);
            }
        }
        $where['article_cate_pid'] = 0;
        $cate = $article->cateList($where,'article_cate_id,article_cate_name');
        $this->assign('cate',$cate);
        $this->assign('info',$info);
        $this->assign('url','/baibu/admin/Article/cateEdit');
        $this->assign('nav','修改分类');
        $this->assign('site_title','修改文章分类-管理后台-百步园艺');
        return $this->fetch('cate_add');
    }

    /**
     * 状态修改
     */
    public function cateStatus(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        $update['article_cate_status'] = $_GET['article_cate_status'];
        $condition['article_cate_id'] = $_GET['article_cate_id'];
        $article = new Articles;
        $result = $article->cateEdit($condition,$update);
        if($result){
            switch ($update['article_cate_status']){
                case 1:
                    $data['img'] = '/baibu/public/static/image/default/dui.png';
                    $data['name'] = "article_cate_id={$condition['article_cate_id']}&article_cate_status=0";
                    break;
                default :
                    $data['img'] = '/baibu/public/static/image/default/cuo.png';
                    $data['name'] = "article_cate_id={$condition['article_cate_id']}&article_cate_status=1";
                    break;
            }
            ajaxReturn($data,'操作成功!',1);
        }else{
            ajaxReturn(0,'操作失败!',0);
        }
    }

    /**
     * 分类删除
     */
    public function cateDel(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        if(gettype($_GET['article_cate_id']) == 'array'){
            $condition['article_cate_id'] = array('in',$_GET['article_cate_id']);
        }else{
            $condition['article_cate_id'] = $_GET['article_cate_id'];
        }
        $article = new Articles;
        $result = $article->cateDel($condition);
        if($result){
            ajaxReturn($_GET['article_cate_id'],'删除成功!',1);
        }else{
            ajaxReturn(0,'删除失败!',0);
        }
    }
}